package com.gxa.eshops.portal.utils;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import java.util.Map;
import java.util.Set;

/**
 * @author bill
 * @date 2022/7/7 16:40
 */
public class RestUtils {

    private static RestTemplate restTemplate;

    static {
        // OkHttp3ClientHttp性能比较好, 需要引入jar
        // restTemplate = new RestTemplate(new OkHttp3ClientHttpRequestFactory());
        restTemplate = new RestTemplate();
    }

    /**
     * 文章与参数
     *
     * @param url     url
     * @param headers 头
     * @param params  参数个数
     * @return {@code Map}
     */
    public static Map<String, Object> postWithParams(String url, Map<String, String> headers, MultiValueMap<String, Object> params) {
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        if (headers != null) {
            Set<Map.Entry<String, String>> entries = headers.entrySet();
            for (Map.Entry<String, String> entry : entries) {
                httpHeaders.set(entry.getKey(), entry.getValue());
            }
        }
        HttpEntity<Object> httpEntity = new HttpEntity<>(params, httpHeaders);
        // 通过post方式发送请求的方法
        @SuppressWarnings("unchecked")
        Map<String, Object> map = restTemplate.postForObject(url, httpEntity, Map.class);
        return map;
    }
}
